<template>
    <div class="container">
        <el-form class="form_box" ref="formRef" :model="form" :rules="rules" label-width="96px">
            <el-form-item label="任务标题" prop="Title">
                <el-input class="title_inp" v-model="form.Title" clearable :show-word-limit="true" maxlength="15" />
            </el-form-item>
            <el-form-item label="添加手机号" class="item_margin" prop="PhoneList">
                <div>
                    <span class="num">{{ form.PhoneList.length || 0 }} </span>/1000
                </div>
            </el-form-item>
            <el-form-item prop="PhoneList" ref="PhoneListRef">
                <el-button @click="onInput">手动输入</el-button>
                <el-button @click="impTable">导入表格</el-button>
                <el-button class="zdy_btn" link @click="onRestPhone">清空</el-button>
                <el-button class="zdy_btn" type="primary" link @click="onDownloadTem">下载模板</el-button>
            </el-form-item>
            <el-form-item>
                <el-input class="mobile_all" v-model="state.PhoneList" type="textarea" :readonly="true" :autosize="true" />
            </el-form-item>
            <el-form-item label="验证消息" prop="VerifyMessage">
                <el-input v-model="form.VerifyMessage" type="textarea" maxlength="50" placeholder="请输入验证消息，最多支持50个字"
                    :show-word-limit="true" :rows="4" />
            </el-form-item>
            <el-form-item label="客户标签">
                <div>
                    <ZWRenderTags v-model:tags="form.CustTagList" @openMore="onSelectTag"></ZWRenderTags >
                    <div :class="form.CustTagList.length ? 'tag_btn' : ''">
                        <el-button @click="onSelectTag">选择标签</el-button>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="自动备注" class="auto_remarks">
                <el-switch v-model="form.AutoRemarks" />
            </el-form-item>
            <el-form-item v-if="form.AutoRemarks" prop="AutoRemarksMsg">
                <el-input id="inputId" v-model="form.AutoRemarksMsg" type="textarea" maxlength="50" placeholder="请添加自动备注内容"
                    :show-word-limit="true" :rows="4" />
                <div class="remarks_btn">
                    <el-button @click="onSetInpCursor('[添加日期]')">添加日期</el-button>
                    <el-button @click="onSetInpCursor('[手机号]')">手机号</el-button>
                    <el-button @click="onSetInpCursor('[昵称]')">昵称</el-button>
                </div>
            </el-form-item>
            <el-form-item>
                <div class="desc">开启后，将对添加的好友在企微中进行备注。</div>
            </el-form-item>
            <el-form-item>
                <el-button @click="onRouteBack">取消</el-button>
                <el-button type="primary" @click="onSubmit(formRef)">确定</el-button>
            </el-form-item>
        </el-form>
    </div>
    <Dialog :state="DialogData" @cancel="DialogData.visible = false" @confirm="onConfirm" @closed="onClosed">
        <div class="dialog_title">输入多个手机号请用“回车”隔开</div>
        <div>
            <el-input v-model="state.phone" type="textarea" placeholder="请输入手机号" :rows="10" />
        </div>
    </Dialog>
    <Dialog :draggable="true" :state="importDialog" @cancel="importDialog.visible = false">
        <el-upload multiple :show-file-list="false" :http-request="onUploadFile">
            <el-button slot="trigger">
                <el-icon class="el-icon--right">
                    <Upload />
                </el-icon>上传文件
            </el-button>
        </el-upload>
        <div class="upload_desc">仅支持上传Excel文件，大小不超过20M</div>
    </Dialog>
    <ZWSelectLabel v-model="labelVisiable" ref="zwSelectLabelRef" @submit="getTagList" />
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

import Dialog from "@renderer/components/dialog";
import ZWSelectLabel from "@renderer/components/win/ZWSelectLabel/ZWSelectLabel.vue";
import ZWRenderTags from '@renderer/components/win/ZWSelectLabel/ZWRenderTags.vue'
import {
    putAutoMakeFriend,
    parseExcelAutoMakeFriend,
    downloadTplAutoMakeFriend,
} from "@renderer/ajax/api/autoAddBuddy";
import { toBuffer } from "@renderer/utils/utils";

const { ipcRenderer } = require("electron");
const fs = require("fs");
const router = useRouter();
const formRef = ref<any>(null);
const state = reactive({
    phone: "", // dialog输入的手机号
    phone2: "", // dialog输入的手机号
    PhoneList: "", // 展示手机号
    CustTagList: [],
});
const form = reactive({
    Id: 0, // ID 不为0 为编辑
    Title: "", // 标题
    PhoneList: [],
    VerifyMessage: "", // 验证信息
    type: [1],
    AddTypeWeiChat: false, // 添加微信客户
    AddTypeWeiWork: false, // 添加企微客户
    CustTagList: [],
    AutoRemarks: true, // 自动备注
    AutoRemarksMsg: "", // 自动备注内容
});
const rules = reactive<any>({
    Title: [{ required: true, message: "请输入任务标题" }],
    PhoneList: [
        { required: true, message: "请添加手机号", trigger: ["blur", "change"] },
    ],
    VerifyMessage: [
        { required: true, message: "请输入验证消息", trigger: "change" },
    ],
    type: [{ required: true, message: "请勾选添加客户类型", trigger: "change" }],
    AutoRemarksMsg: [
        { required: true, message: "请添加自动备注内容", trigger: "blur" },
    ],
    date1: [
        { type: "date", required: true, message: "请选择日期", trigger: "change" },
    ],     
    date2: [
        { type: "date", required: true, message: "请选择日期", trigger: "change" },
    ],
    desc: [{ required: true, message: "请输入验证消息", trigger: "blur" }],
});
// 选择标签
const zwSelectLabelRef = ref<any>(null);
const labelVisiable = ref(false)
const onSelectTag = () => {
    zwSelectLabelRef.value.open(form.CustTagList);
};
const getTagList = (v: any) => {
    form.CustTagList = v;
};
// 手动输入
const DialogData = reactive({
    width: "600px",
    visible: false,
    title: "输入手机号",
    footer: ["取消", "确定", "center"],
});
// 打开手动输入dialog
const onInput = () => {
    state.phone = state.phone2;
    DialogData.visible = true;
};
const PhoneListRef = ref<any>(null);
const onClosed = () => {
    console.log("关闭回调");
    PhoneListRef.value.clearValidate();
};
const onConfirm = () => {
    console.log("确定回调");
    let rex = /^1[3456789]\d{9}$/;
    let str = "";
    let flag = true;
    let PhoneList = [];
    state.phone.split("\n").forEach((item, index) => {
        if (rex.test(item)) {
            if (str.includes(item)) {
                ElMessage.warning(`第${index + 1}行手机号重复`);
                flag = false;
            } else {
                if (form.PhoneList.length < 1000) {
                    str += item + "、";
                    PhoneList.push(item);
                }
            }
        } else {
            flag = false;
            ElMessage.error(`第${index + 1}行手机号格式不正确`);
        }
    });
    if (flag) {
        DialogData.visible = false;
        state.phone2 = state.phone;
        state.PhoneList = str.slice(0, -1);
        form.PhoneList = PhoneList;
    }
    console.log(str);
};
// 导入表格
const importDialog = reactive({
    width: "600px",
    visible: false,
    title: "导入表格",
    footer: ["取消", "确定", "center"],
    value: "",
});
const impTable = () => {
    importDialog.visible = true;
};
const onUploadFile = async (file: any) => {
    const formData = new FormData();
    formData.append("path", file.file);
    console.log(file, "file");
    // formData.append('userId', activeIds.userId)
    // const filePath: any = await getSelectFilePath({ FileName: '', DefaultExt: '' })
    // if (!filePath) return
    // if ('xlsxXLSX'.includes(filePath.split('.').at(-1))) {
    const res: any = await parseExcelAutoMakeFriend(formData);
    onRestPhone();
    // 过滤假值
    let rex = /^1[3456789]\d{9}$/d;
    let newArr = [...new Set(res)];
    form.PhoneList = newArr.filter((item) => rex.test(item));
    form.PhoneList.forEach((item: any) => {
        state.PhoneList += `${item}、`;
        state.phone2 += `${item}\n`;
        state.phone += `${item}\n`;
    });
    // 删除最后一个逗号
    state.PhoneList = state.PhoneList.slice(0, -1);
    state.phone2 = state.phone2.slice(0, -1);
    state.phone = state.phone.slice(0, -1);
    importDialog.visible = false;
    ElMessage.success("导入成功");
    formRef.value?.validateField(['PhoneList'])
    // } else {
    //   ElMessage.error('请选择Excel文件')
    // }
};

// 清空手机号
const onRestPhone = () => {
    form.PhoneList = [];
    state.PhoneList = "";
    state.phone = "";
    state.phone2 = "";
};
// 下载模板
const onDownloadTem = async () => {
    const res: any = await downloadTplAutoMakeFriend();
    let params = {
        title: "请选择下载文件的目录",
        buttonLabel: "保存",
        pathName: "模板.xlsx",
    };
    let buf = toBuffer(res);
    ipcRenderer.invoke("open-savebox", params).then((res) => {
        console.log(res, "1");
        fs.writeFileSync(res.filePath, buf);
        res && ElMessage.success("下载成功");
    });
};

const handlePreview = (file) => {
    console.log(file);
};

const onSetInpCursor = (v: any) => {
    const ElRef: any = document.getElementById("inputId");
    const inpIndex = ElRef.selectionStart;
    const start = `${form.AutoRemarksMsg.substring(0, inpIndex)}${v}`;
    const end = form.AutoRemarksMsg.substring(
        inpIndex,
        form.AutoRemarksMsg.length
    );
    form.AutoRemarksMsg = `${start}${end}`;
    ElRef.focus();
    nextTick(() => {
        ElRef.selectionStart = start.length;
        ElRef.selectionEnd = start.length;
        formRef.value?.validateField(['AutoRemarksMsg'])
    });
};
// 返回
const onRouteBack = () => {
    router.back();
};
const onSubmit = (formEl: any) => {
    console.log("submit!");
    formEl.validate((valid: any) => {
        if (valid) {
            let params = {
                Title: form.Title,
                PhoneList: form.PhoneList,
                VerifyMessage: form.VerifyMessage,
                AddTypeWeiChat: form.type.includes(1),
                AddTypeWeiWork: form.type.includes(2),
                CustTagList: form.CustTagList.map(item => item.Id),
                AutoRemarks: form.AutoRemarks,
                AutoRemarksMsg: form.AutoRemarksMsg,
            };
            params = JSON.parse(JSON.stringify(params));
            console.log("请求参数", params);
            putAutoMakeFriend(params).then((res: any) => {
                const message = form.Id ? "编辑任务成功" : "新建任务成功";
                ElMessage.success(message);
                onRouteBack();
            });
        }
    });
};
</script>

<style scoped lang="scss">
.title_inp {
    width: 300px;
}

.desc {
    margin: -16px 0 -12px;
    font-size: 12px;
    color: #999;
}

.zdy_btn {
    padding: 0;
}

.upload_desc {
    margin-top: 10px;
}

.container {
    background: #fff;
    padding: 16px;

    .form_box {
        width: 60%;
    }

    .num {
        color: #1432f5;
    }

    .clear {
        margin-left: 5px;
        cursor: pointer;

        &:hover {
            color: red;
        }
    }

    .item_margin {
        margin-bottom: 0;
    }

    .download {
        margin-left: 10px;
        color: #1432f5;
        cursor: pointer;
    }
}

.auto_remarks {
    margin-bottom: 10px;
}

.remarks_btn {
    margin-top: 10px;
}

.mobile_all {
    background: red;

    :deep(.el-textarea__inner) {
        border-radius: 0;
        cursor: default;

        &:hover {
            border: none;
        }
    }
}

.dialog_title {
    margin-bottom: 10px;
}

.tag_list {
    margin-bottom: 10px;

    .tag {
        margin-right: 10px;
    }
}

.tag_btn {
    margin-top: 12px;
}
</style>
